import Request from '@/common/luch-request/index.js'
import constants from '@/common/util/constants.js'
import configService from './config.service.js'
import tip from '@/common/util/tip.js';
import store from '@/store/index.js';


const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync(constants.ACCESS_TOKEN)
	} catch (e) {
		console.log("getTokenStorage", token)
	}
	return token
}


const http = new Request()
http.setConfig((config) => {
	config.baseUrl = configService.BASE_URL
	config.header = {
		...config.header
	}
	return config
})

http.validateStatus = (statusCode) => {
	return statusCode === 200
}
http.interceptor.request((config, cancel) => {
	tip.loading()
	config.header = {
		...config.header,
		'ProjectsId': constants.PROJECTS_ID,
		'App-Id': constants.APP_ID,
		'App-Key': constants.APP_KEY,
		'Content-Type': 'application/json;charset=UTF-8',
		'Sign': 'MD5=11111',
		'Access-Token': getTokenStorage()
	}
	return config
})

http.interceptor.response(async (response) => {
	var res = response.data
	tip.loaded()
	if (res.code !== 200) {
		if (res.code === 500) {
			tip.alert(res.data);
		} else if (res.code === 501) {
			var html = ''
			var data = res.data
			for (var item in data) {
				html += `【${item}】<m style="color:red">${data[item]}</m><br>`
			}
			console.log(html)
		} else if (res.code === 502) {
			console.log((res))
			tip.alert('缺少令牌！');
			uni.navigateTo({
			  url: "/pages/login/index"
			})
		} else if (res.code === 506003) {
			tip.alert('令牌失效！');
			uni.navigateTo({
			  url: "/pages/login/index"
			})
		} else {
			var message = res.data == null ? res.message : res.data
			tip.alert(message);
		}

		return Promise.reject(res)
	} else {
		return res.data
	}
}, (response) => {
	if (response) {
		let data = response.data
		console.log((response.errMsg))
	}
	return response
})

export {
	http
}
